package com.taotao.rop.service;

import com.rop.annotation.HttpAction;
import com.rop.annotation.NeedInSessionType;
import com.rop.annotation.ServiceMethod;
import com.rop.annotation.ServiceMethodBean;
import com.rop.session.SimpleSession;
import com.taotao.admin.MyRopClient;
import com.taotao.rop.database.Constant;
import com.taotao.rop.database.domain.WechatArticle;
import com.taotao.rop.database.domain.WechatResp;
import com.taotao.rop.database.domain.WechatRespArticle;
import com.taotao.rop.database.mapper.WechatArticleMapper;
import com.taotao.rop.database.mapper.WechatRespArticleMapper;
import com.taotao.rop.database.mapper.WechatRespMapper;
import com.taotao.rop.manager.RopSessionManager;
import com.taotao.rop.response.BaseResponse;
import com.taotao.wechat.util.MessageUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;
import java.util.List;

@ServiceMethodBean(httpAction = HttpAction.POST, version = "1.0")
public class WechatRespService {
    @Autowired
    private WechatRespMapper respMapper;
    @Autowired
    private WechatRespArticleMapper respArticleMapper;
    @Autowired
    private WechatArticleMapper articleMapper;

    @ServiceMethod(method = "wechatResp.insert")
    public Object insertWechatResp(WechatResp request) {
        Date now = new Date();
        request.setCreateTime(now);
        request.setLastChangedTime(now);
        Long sessionUserId = (Long) ((SimpleSession)request.getRopRequestContext().getSession()).getAttribute(RopSessionManager.KEY_MANAGER_ID);
        request.setCreateUserId(sessionUserId);
        request.setLastChangedUserId(sessionUserId);
        request.setStatus(Constant.STATUS_ENABLE);
        Integer id = respMapper.insertOne(request);
        RespSearchService.getInstance().addIndex(request);

        BaseResponse<Integer> response = new BaseResponse<Integer>();
        response.setSuccess(true);
        response.setData(id);
        return response;
    }

    @ServiceMethod(method = "wechatResp.update")
    public Object updateWechatResp(WechatResp request) {
        request.setLastChangedTime(new Date());
        request.setLastChangedUserId((Long) ((SimpleSession)request.getRopRequestContext().getSession()).getAttribute(RopSessionManager.KEY_MANAGER_ID));
        Integer id = respMapper.updateOne(request);
        RespSearchService.getInstance().updateIndex(request);

        BaseResponse<Integer> response = new BaseResponse<Integer>();
        response.setSuccess(true);
        response.setData(id);
        return response;
    }

    @ServiceMethod(method = "wechatResp.list")
    public Object getWechatRespByPage(WechatResp request) {
        String appId = ((SimpleSession)request.getRopRequestContext().getSession()).getAttribute(RopSessionManager.KEY_APP_ID).toString();
        if (!appId.equalsIgnoreCase(MyRopClient.APP_ID)) {
            request.setAppId(appId);
        }
        List<WechatResp> respList = respMapper.getListByPage(request);
        for (WechatResp resp : respList) {
            //如果响应消息为图文
            if (MessageUtil.RESP_MESSAGE_TYPE_NEWS.equalsIgnoreCase(resp.getMsgType())) {
                WechatRespArticle condition = new WechatRespArticle();
                condition.setRespId(resp.getId());
                //通过关系表
                List<WechatRespArticle> respArticleList = respArticleMapper.getList(condition);
                for (WechatRespArticle respArticle : respArticleList) {
                    WechatArticle articleCondition = new WechatArticle();
                    articleCondition.setId(respArticle.getArticleId());
                    articleCondition.setStatus(Constant.STATUS_ENABLE);
                    //取得图文
                    List<WechatArticle> articleList = articleMapper.getList(articleCondition);
                    for (WechatArticle article : articleList) {
                        WechatArticle subArticleCondition = new WechatArticle();
                        subArticleCondition.setParentId(article.getId());
                        subArticleCondition.setStatus(Constant.STATUS_ENABLE);
                        //尝试取得多图文的其他图文，如果未取到，则是单图文
                        List<WechatArticle> subArticleList = articleMapper.getList(subArticleCondition);
                        if (subArticleList != null && subArticleList.size() > 0) {
                            article.setSubArticleList(subArticleList);
                        }
                        //完成获取图文消息
                        resp.setArticleList(articleList);
                    }
                }
            }
        }

        BaseResponse<List<WechatResp>> response = new BaseResponse<List<WechatResp>>();
        response.setSuccess(true);
        response.setMsg("" + respMapper.getCount(request));
        response.setData(respList);
        return response;
    }

    @ServiceMethod(method = "wechatResp.listAll", needInSession = NeedInSessionType.NO)
    public Object getAllWechatResp(WechatResp request) {
        if (request.getRopRequestContext().getSession() != null
                && (request.getAppId() == null || request.getAppId().length() == 0)) {
            String appId = ((SimpleSession) request.getRopRequestContext().getSession()).getAttribute(RopSessionManager.KEY_APP_ID).toString();
            if (!appId.equalsIgnoreCase(MyRopClient.APP_ID)) {
                request.setAppId(appId);
            }
        }
        List<WechatResp> respList = respMapper.getList(request);
        for (WechatResp resp : respList) {
            //如果响应消息为图文
            if (MessageUtil.RESP_MESSAGE_TYPE_NEWS.equalsIgnoreCase(resp.getMsgType())) {
                findNews(resp);
            } else if (MessageUtil.RESP_MESSAGE_TYPE_TEXT.equalsIgnoreCase(resp.getMsgType())) {
                //欢迎语和默认应答语是否追加默认信息
                if(resp.getAddDefault() == 1) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(resp.getContent());
                    if (resp.getKeyvalue().equals("default")
                            || resp.getKeyvalue().equals("welcome")) {
                        WechatResp condition = new WechatResp();
                        condition.setKeyvalue(resp.getKeyvalue());
                        condition.setAppId(MyRopClient.APP_ID);
                        List<WechatResp> defaults = respMapper.getList(condition);
                        if (defaults != null && defaults.size() > 0) {
                            sb.append("\n");
                            sb.append(defaults.get(0).getContent());
                        }
                    }
                    resp.setContent(sb.toString());
                }
            }
        }

        BaseResponse<List<WechatResp>> response = new BaseResponse<List<WechatResp>>();
        response.setSuccess(true);
        response.setMsg("" + respMapper.getCount(request));
        response.setData(respList);
        return response;
    }

    @ServiceMethod(method = "wechatResp.searchByKeyvalue", needInSession = NeedInSessionType.NO)
    public Object searchWechatRespByKeyvalue(WechatResp request) {
        //根据keyvalue必定只获取到一条应答消息
        WechatResp theResp = new WechatResp();
        StringBuilder sb = new StringBuilder();
        StringBuilder sub = new StringBuilder();

        //根据keyvalue获取非默认应答信息
        WechatResp condition = new WechatResp();
        condition.setStatus(Constant.STATUS_ENABLE);
        condition.setKeyvalue(request.getKeyvalue());
        condition.setAppId(request.getAppId());
        List<WechatResp> respList = respMapper.getList(condition);

        //如果有非默认应答，采用非默认的，否则，采用默认应答
        if (respList != null && respList.size() > 0) {
            setResp(theResp, respList, condition, request, sb, sub);
        } else if (!request.getAppId().equalsIgnoreCase(MyRopClient.APP_ID)){
            condition.setKeyvalue(request.getKeyvalue());
            condition.setAppId(MyRopClient.APP_ID);
            respList = respMapper.getList(condition);
            if (respList != null && respList.size() > 0) {
                setResp(theResp, respList, condition, request, sb, sub);
            }
        }

        //设置应答消息内容
        if (StringUtils.isNotBlank(theResp.getMsgType())) {
            if (theResp.getMsgType().equalsIgnoreCase("text")) {
                theResp.setContent(sb.append(sub).toString());
            } else if (theResp.getMsgType().equalsIgnoreCase("news")) {
                findNews(theResp);
            }
        }

        BaseResponse<WechatResp> response = new BaseResponse<WechatResp>();
        response.setSuccess(true);
        response.setData(theResp);
        return response;
    }

    @ServiceMethod(method = "wechatResp.find")
    public Object findWechatResp(WechatResp request) {
        List<WechatResp> respList = respMapper.getList(request);
        for (WechatResp resp : respList) {
            //如果响应消息为图文
            if (MessageUtil.RESP_MESSAGE_TYPE_NEWS.equalsIgnoreCase(resp.getMsgType())) {
                WechatRespArticle condition = new WechatRespArticle();
                condition.setRespId(resp.getId());
                //通过关系表
                List<WechatRespArticle> respArticleList = respArticleMapper.getList(condition);
                for (WechatRespArticle respArticle : respArticleList) {
                    WechatArticle articleCondition = new WechatArticle();
                    articleCondition.setId(respArticle.getArticleId());
                    articleCondition.setStatus(Constant.STATUS_ENABLE);
                    //取得图文
                    List<WechatArticle> articleList = articleMapper.getList(articleCondition);
                    for (WechatArticle article : articleList) {
                        WechatArticle subArticleCondition = new WechatArticle();
                        subArticleCondition.setParentId(article.getId());
                        subArticleCondition.setStatus(Constant.STATUS_ENABLE);
                        //尝试取得多图文的其他图文，如果未取到，则是单图文
                        List<WechatArticle> subArticleList = articleMapper.getList(subArticleCondition);
                        if (subArticleList != null && subArticleList.size() > 0) {
                            article.setSubArticleList(subArticleList);
                        }
                        //完成获取图文消息
                        resp.setArticleList(articleList);
                    }
                }
            }
        }

        BaseResponse<List<WechatResp>> response = new BaseResponse<List<WechatResp>>();
        response.setSuccess(true);
        response.setMsg("" + respMapper.getCount(request));
        response.setData(respList);
        return response;
    }

    /**
     * 取得图文消息详情，为resp添加articleList属性值
     * @param resp 要取得图文消息的应答
     */
    private void findNews(WechatResp resp) {
        WechatRespArticle condition = new WechatRespArticle();
        condition.setRespId(resp.getId());
        //通过关系表
        List<WechatRespArticle> respArticleList = respArticleMapper.getList(condition);
        for (WechatRespArticle respArticle : respArticleList) {
            WechatArticle articleCondition = new WechatArticle();
            articleCondition.setId(respArticle.getArticleId());
            articleCondition.setStatus(Constant.STATUS_ENABLE);
            //取得图文
            List<WechatArticle> articleList = articleMapper.getList(articleCondition);
            for (WechatArticle article : articleList) {
                WechatArticle subArticleCondition = new WechatArticle();
                subArticleCondition.setParentId(article.getId());
                subArticleCondition.setStatus(Constant.STATUS_ENABLE);
                //尝试取得多图文的其他图文，如果未取到，则是单图文
                List<WechatArticle> subArticleList = articleMapper.getList(subArticleCondition);
                if (subArticleList != null && subArticleList.size() > 0) {
                    article.setSubArticleList(subArticleList);
                }
                //完成获取图文消息
                resp.setArticleList(articleList);
            }
        }
    }

    private void setResp(WechatResp theResp, List<WechatResp> respList, WechatResp condition, WechatResp request, StringBuilder sb, StringBuilder sub) {
        theResp.setId(respList.get(0).getId());
        theResp.setMsgType(respList.get(0).getMsgType());
        //如果是菜单，则拼接子菜单；否则，直接返回内容
        if(respList.get(0).getIsMenu() == 1) {
            if (request.getKeyvalue().equalsIgnoreCase("default")
                    || request.getKeyvalue().equalsIgnoreCase("welcome")) {
                sb.append(respList.get(0).getContent())
                        .append("\n").append("您也可以选择以下业务了解详情，请回复序号：");
            } else {
                sb.append(respList.get(0).getContent())
                        .append("包含以下内容，请回复序号进行")
                        .append(respList.get(0).getContent()).append("：");
            }

            List<WechatResp> subRespList;
            for (int i = 1; i <= 9; i++) {
                //如果有非默认应答，采用非默认的，否则，采用默认应答
                if (request.getKeyvalue().equalsIgnoreCase("default")
                        || request.getKeyvalue().equalsIgnoreCase("welcome")) {
                    condition.setKeyvalue("" + i);
                } else {
                    condition.setKeyvalue(request.getKeyvalue() + i);
                }
                condition.setAppId(request.getAppId());
                subRespList = respMapper.getList(condition);
                if (subRespList != null && subRespList.size() > 0) {
                    sub.append("\n")
                            .append(subRespList.get(0).getKeyvalue()).append("、")
                            .append(subRespList.get(0).getShortTitle());
                } else if (!request.getAppId().equalsIgnoreCase(MyRopClient.APP_ID)){
                    condition.setAppId(MyRopClient.APP_ID);
                    subRespList = respMapper.getList(condition);
                    if (subRespList != null && subRespList.size() > 0){
                        sub.append("\n")
                                .append(subRespList.get(0).getKeyvalue()).append("、")
                                .append(subRespList.get(0).getShortTitle());
                    }
                }
            }
        } else {
            sb.append(respList.get(0).getContent());
        }
    }

    /**
     * 为【内蒙古移动营业厅】微信号服务
     */
    @Scheduled(cron = "0 0 0 1 1 ?")
    public void generateWelcomeAndDefaultForGame() {
        String appId = "wx940fdc566fac172a";
        addOrUpdateWelcomeAndDefault("welcome", appId, "亲~等您好久啦！现在您可以回复数字【9】，了解活动详情，也可以直接输入【找4G】参与活动，您也可以【按住说话】大吼出您要办理或了解的业务，");
    }

    /**
     * 为【内蒙古移动营业厅】微信号服务
     */
    @Scheduled(cron = "0 0 0 23 3 ?")
    public void recoverWelcomeAndDefaultFromGame() {
        String appId = "wx940fdc566fac172a";
        addOrUpdateWelcomeAndDefault("welcome", appId, "亲~等您好久啦！现在您可以【按住说话】大吼出您要办理或了解的业务，");
    }

    private synchronized void addOrUpdateWelcomeAndDefault(String key, String appId, String content) {
        WechatResp condition = new WechatResp();
        condition.setKeyvalue(key);
        condition.setKeyword(key);
        condition.setAppId(appId);
        condition.setStatus(Constant.STATUS_ENABLE);
        List<WechatResp> respList = respMapper.getList(condition);

        condition.setContent(content);
        condition.setMsgType("text");
        Date now = new Date();
        condition.setLastChangedTime(now);
        condition.setLastChangedUserId(1L);
        if (respList != null && respList.size() > 0) {
            //update
            condition.setId(respList.get(0).getId());
            respMapper.updateOne(condition);
            RespSearchService.getInstance().updateIndex(condition);
        } else {
            //add
            condition.setCreateTime(now);
            condition.setCreateUserId(1L);
            condition.setPriority(0);
            condition.setAddDefault(0);
            condition.setIsMenu(1);
            condition.setShortTitle("内蒙古移动欢迎您~");
            respMapper.insertOne(condition);
            RespSearchService.getInstance().addIndex(condition);
        }
    }
}
